"""健康检查应用视图模块

定义了处理健康检查相关HTTP请求的视图函数。
"""

from django.core.cache import cache
from django.db import connections
from django.http import JsonResponse


def liveness(request):
    """存活检查端点，用于确定应用是否正在运行"""
    # 执行检查以确定应用是否存活
    return JsonResponse({"status": "alive"})


def readiness(request):
    """就绪检查端点，用于确定应用是否准备好接收流量"""
    try:
        # 检查数据库连接
        connections["default"].cursor()

        # 检查缓存（如Redis）连接
        cache.set("health_check", "ok", timeout=10)
        if cache.get("health_check") != "ok":
            raise ValueError("Failed to communicate with cache backend")

        return JsonResponse({"status": "healthy"}, status=200)
    except Exception as e:
        return JsonResponse({"status": "unhealthy", "error": str(e)}, status=500)
